package com.example.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;

/**
 * @author long
 * @date 2023/9/19 14:28
 */
@Component
public class ApplicationUtils implements ApplicationContextAware {

    private static ApplicationContext context;

    public static Object getBean(Class clazz){
        return context.getBean(clazz);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationUtils.context = applicationContext;
    }

    public static void publishEvent(ApplicationEvent event){
        context.publishEvent(event);
    }

    public static <T> T getBeanByClass(Class<T> clazz){
        return context.getBean(clazz);
    }

    public static <T>  T getBeanByName(String beanName){
        return (T)context.getBean(beanName);
    }

}
